package com.zhuyuan.controller;

import com.zhuyuan.Entity.Person;
import com.zhuyuan.common.R;
import com.zhuyuan.dto.PersonDto;
import com.zhuyuan.repository.PersonRepository;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/person")
@Slf4j
@Api(tags = "个人信息相关接口")
public class PersonController {
    @Autowired
    private PersonRepository personRepository;

    @GetMapping("/findAll")
    @ApiOperation("查询前五个用户,未使用")
    public R<List<Person>> findAll(){
        // 示例：按年龄字段降序排列查询前5个用户
        List<Person> people = personRepository.findAll(Sort.by(Sort.Direction.ASC,"id")).stream().limit(5).collect(Collectors.toList());
        return R.success(people);
    }

    @PostMapping("/submitForm")
    @ApiOperation("用户的新增，修改")
    public R<String> submitForm(@RequestBody Person person){
        log.info("新增/修改：{}",person);
        personRepository.save(person);
        return R.success("新增/修改,成功");
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation("根据id删除用户")
    public R<String> delete(@ApiParam("ID") @PathVariable Integer id){
        log.info("删除：{}",id);
        personRepository.deleteById(id);
        return R.success("删除成功");
    }

    @GetMapping("/items")
    @ApiOperation("分页查询")
    public R<PersonDto> items(Integer page, Integer limit){
        log.info("要查询的页码, 每页的记录数：{},{}",page,limit);

        Pageable pageable = PageRequest.of(page - 1, limit);

        Page<Person> personPage = personRepository.findAll(pageable);

        List<Person> personList = personPage.getContent();

        PersonDto personDto = new PersonDto(personList,personPage.getTotalElements());

        return R.success(personDto);
    }
}
